package org.windey.client;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

/**
 * 
 * klasse om data te voorzien aan de server
 * data == screenshots
 *
 */
public class WindeyClientDataProvider extends Thread
{
	private Robot robot;
	/**
	 * lijst met images
	 */
	private ArrayList<String> buffer;
	private WindeyClientThreadInterface wcti;
	private BufferedImage screenImage;
	private Rectangle screenRect;
	private int width, height;
	
	/**
	 * 
	 * @param wcti
	 * @throws WindeyClientDataProviderException
	 */
	public WindeyClientDataProvider(WindeyClientThreadInterface wcti) throws WindeyClientDataProviderException
	{
		this.wcti = wcti;
		screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
		try
		{
			robot = new Robot();
		}
		catch (AWTException e)
		{
			e.printStackTrace();
			throw new WindeyClientDataProviderException();
		}
		buffer = new ArrayList<String>();
		width = screenRect.width/2;
		height = screenRect.height/2;
		screenImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY) ;
	}
	
	/**
	 * om data aan te maken
	 */
	public void run()
	{
		String line = "";
		while (wcti.isStreaming())
		{
			newImage();
			for (int y = 0; y < height; y++)
			{
				line = y +  ":";
				for (int x = 0; x < width; x++)
				{
					line += screenImage.getRGB(x, y) + ",";
				}
				buffer.add(line);
			}
			while (buffer.size() > height)
			{
				try {
					WindeyClientDataProvider.sleep(100) ;
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			if (buffer.size() > height*2) {
				buffer.clear() ;
			}
		}
	}
	
	public int getBufferSize() {
		return buffer.size() ;
	}
	
	public void newImage()
	{
		Image a = robot.createScreenCapture(screenRect).getScaledInstance(screenRect.width/2, -1, NORM_PRIORITY);
		screenImage.getGraphics().drawImage(a, 0 , 0, width, height, null);
		//screenImage = robot.createScreenCapture(screenRect) ;
 	}
	
	/**
	 * 
	 * @return de volgende image in de buffer
	 */

	public String getNextDataString()
	{
		String result;
		try
		{
			result = buffer.get(0);
			buffer.remove(0);
		}
		catch (IndexOutOfBoundsException e)
		{
			result = "0";
		}
		return result;
	}
}
